const mongoose = require("mongoose");
const request = require("request");

var config = require("../config/config.js");

var Merchant = mongoose.model("merchant");
var Food = mongoose.model("food");

//WS获取所有白名单商家[{merchant}]
exports.getAllMerchants = function (req, res) {
    var mStatus = req.query.mStatus;
    console.log(mStatus);
    //测试读数据库
    request(config.wsGetWhiteListMerchantUrl + mStatus, function (err, response, body) {
        var b = JSON.parse(body);
        var m = [];
        var returnMerchant =[];
        Food.find({}, function (err, foods) {
            for (var fkey in foods) {
                for (var key in b) {
                    if (b[key].mId == foods[fkey].mId) {
                        if (!(m.indexOf(b[key]) >= 0)) {
                            m.push(b[key]);
                            break;
                        }

                    }
                }
            }
            Merchant.find({},function (err,merchants) {
                for(var i in merchants){
                    for(var key in m){
                        if(merchants[i]._id == m[key].mId){
                            var tempMerchant = JSON.stringify(merchants[i]);
                            tempMerchant = JSON.parse(tempMerchant);
                            delete tempMerchant.mPassword;
                            returnMerchant.push(tempMerchant);
                        }
                    }
                }
                console.log(returnMerchant);
                res.json(returnMerchant);
            })



        });


    })
};

exports.getMerchantById = function (req, res) {
    var mId = req.params.mId;
    Merchant.findOne({_id: mId}, "-mPassword -mIdCard -mCardPath -mPersonName", function (err, merchant) {
        if (!err) {
            req.session.merchant = merchant;
            console.log(req.session.merchant);
            res.json(merchant);
        } else {
            res.json({"error": "getMerchantById"})
        }
    })
}

